package com.cqfae.deploycentral.app.web.controller;

/**
 * Created by YANGHENG940 on 2017/7/12.
 */

import com.cqfae.deploycentral.app.config.DeployInfo;
import com.cqfae.deploycentral.app.utils.GsonUtils;
import com.cqfae.deploycentral.app.base.BaseConstantCode;
import com.cqfae.deploycentral.app.dao.entity.DeployHistory;
import com.cqfae.deploycentral.app.services.CommonControllerService;
import com.cqfae.deploycentral.app.services.DeployHistoryService;
import com.cqfae.deploycentral.app.services.JenkinsService;
import com.cqfae.deploycentral.app.services.WindowPlansService;
import com.cqfae.deploycentral.app.utils.NullUtil;
import com.cqfae.deploycentral.app.web.request.DeployActionRequest;
import com.cqfae.deploycentral.app.web.request.JenkinsLogRequest;
import com.cqfae.deploycentral.app.web.request.JenkinsNotifyRequest;
import com.cqfae.deploycentral.app.web.request.WindowPlansRequest;
import com.cqfae.deploycentral.app.web.response.IPage;
import com.cqfae.deploycentral.app.web.response.WebResponse;
import com.cqfae.deploycentral.app.web.vo.DeployHistoryVo;
import com.cqfae.deploycentral.app.web.vo.ProdDeployVo;
import com.cqfae.deploycentral.app.web.vo.WindowPlansVo;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>生产部署controller</p>
 *
 * @author yangheng@cmhk.com
 * @since 1.0.0-snapshot
 */
@RestController
@RequestMapping("/deploy-central/prod/")
public class ProdDeployController implements CommonControllerService<Object> {

    private static Logger logger = LoggerFactory.getLogger(ProdDeployController.class);

    @Autowired
    private WindowPlansService windowPlansService;

    @Autowired
    private DeployHistoryService deployHistoryService;

    @Autowired
    private JenkinsService jenkinsService;

    @Autowired
    private DeployInfo deployInfo;

    @RequestMapping(value = "/deploy/info")
    public WebResponse deployInfo(WindowPlansRequest request) {
        String logJson = GsonUtils.getInstance().toJson(request);
        logger.info("==== deployInfo WindowPlansRequest :==== {}", logJson);
        IPage<WindowPlansVo> ipage = windowPlansService.page(request);
        IPage<ProdDeployVo> ipageVo = GsonUtils.getInstance().fromJson(GsonUtils.getInstance().toJson(ipage),
                new TypeToken<IPage<ProdDeployVo>>() {
                }.getType());
        return getWebResponse(ipageVo);
    }

    /**
     * 查询当天
     *
     * @return
     */
    @RequestMapping(value = "/deploy/info-today")
    public WebResponse deployInfoToday() {
        WindowPlansRequest request = new WindowPlansRequest();
        // 取得今天的日期
        int today = Integer.parseInt(new SimpleDateFormat("yyyyMMdd").format(new Date()));
        // 设置日期范围为今天
        request.setBeginDate(today);
        request.setEndDate(today);
        // 查询
        IPage<WindowPlansVo> ipage = windowPlansService.page(request);
        IPage<ProdDeployVo> ipageVo = GsonUtils.getInstance().fromJson(GsonUtils.getInstance().toJson(ipage),
                new TypeToken<IPage<ProdDeployVo>>() {
                }.getType());
        return getWebResponse(ipageVo);
    }

    //deployAction 一键发布
    @RequestMapping(value = "/deploy/action")
    public WebResponse deployAction(@RequestBody DeployActionRequest request) {
        String logJson = GsonUtils.getInstance().toJson(request);
        logger.info("==== deployAction DeployActionRequest :==== {}", logJson);
        return getWebResponse(windowPlansService.deployAction(request));
    }

    //单个发布
    @RequestMapping(value = "/deploy/actionOne")
    public WebResponse deployActionOne(@RequestBody DeployActionRequest request) {
        String logJson = GsonUtils.getInstance().toJson(request);
        logger.info("==== deployAction DeployActionRequest :==== {}", logJson);
        Assert.isTrue(request.getReportTagId() != null, "reportTagId is null");
        return getWebResponse(windowPlansService.deployActionOne(request));
    }

    @RequestMapping(value = "/deploy/cleanQueue")
    public WebResponse cleanQueue(@RequestBody DeployActionRequest request) {
        String logJson = GsonUtils.getInstance().toJson(request);
        logger.info("==== deployAction cleanQueue :==== {}", logJson);
        return getWebResponse(windowPlansService.cleanQueue(request), "重置成功！");
    }

    //notify
    @RequestMapping(value = "/jenkins/notify")
    public WebResponse jenkinsNotify(JenkinsNotifyRequest request) {
        String logJson = GsonUtils.getInstance().toJson(request);
        logger.info("==== jenkinsNotify JenkinsNotifyRequest :==== {}", logJson);
        DeployHistory dhi = deployHistoryService.updateByCallBack(request);
        //回滚成功直接返回
        if (request.getStatus() == BaseConstantCode.DEPLOY_ROLLBACK_FAIL ||
                request.getStatus() == BaseConstantCode.DEPLOY_ROLLBACK_SUCCESS) {
            return getWebResponse(dhi);
        }
        DeployHistoryVo vo = new DeployHistoryVo(dhi.getDeployStatus());
        BeanUtils.copyProperties(dhi, vo);
        deployHistoryService.changeDeployStatusAndMail(vo);
        return getWebResponse(dhi);
    }

    @RequestMapping(value = "/deploy/rollback")
    public WebResponse rollback(@RequestBody DeployActionRequest request) {//action=rollback
        String logJson = GsonUtils.getInstance().toJson(request);
        logger.info("==== deployInfo WindowPlansRequest :==== {}", logJson);
        return getWebResponse(windowPlansService.deployActionEx(request,deployInfo.getRollback()), "回滚中...");
    }

    @RequestMapping(value = "/deploy/stopApp")
    public WebResponse stopApp(@RequestBody DeployActionRequest request) {//action=stopApp
        String logJson = GsonUtils.getInstance().toJson(request);
        logger.info("==== deployInfo WindowPlansRequest :==== {}", logJson);
        return getWebResponse(windowPlansService.deployActionEx(request,deployInfo.getStopApp()), "停止应用中...");
    }

    @RequestMapping(value = "/deploy/startApp")
    public WebResponse startApp(@RequestBody DeployActionRequest request) {//action=stopApp
        String logJson = GsonUtils.getInstance().toJson(request);
        logger.info("==== deployInfo WindowPlansRequest :==== {}", logJson);
        return getWebResponse(windowPlansService.deployActionEx(request,deployInfo.getStartApp()), "启动应用中...");
    }

    @RequestMapping(value = "/deploy/get-log")
    public WebResponse getLog(JenkinsLogRequest request) {

        logger.info("==== ProdDeployController getLog :==== ");
        Assert.isTrue(StringUtils.isNotBlank(request.getAppName()), "获取日志项目名称不能为空");

        return getWebResponse(jenkinsService.getLog(request.getAppName()));
    }

    /**
     * 手动翻转项目为完成状态
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/deploy/done-one")
    public WebResponse deployDoneOne(@RequestBody DeployActionRequest request) {
        String logJson = GsonUtils.getInstance().toJson(request);
        logger.info("==== /deploy-central/prod/deploy/done-one DeployActionRequest :==== {}", logJson);
        Assert.isTrue(request.getReportTagId() != null, "reportTagId is null");
        Assert.isTrue(StringUtils.isNotBlank(request.getReportCode()), "reportCode is null");
        return getWebResponse(windowPlansService.deployDoneOne(request));
    }

    @Override
    public WebResponse getWebResponse(Object obj) {
        WebResponse webResponse = new WebResponse();
        if (NullUtil.isNotEmpty(obj)) {
            webResponse.setData(obj);
        }
        return webResponse;
    }

    public WebResponse getWebResponse(Object obj, String msg) {
        WebResponse webResponse = new WebResponse();
        webResponse.setResultMessage(msg);
        if (NullUtil.isNotEmpty(obj)) {
            webResponse.setData(obj);
        }
        return webResponse;
    }
}
